/**
 * Created by WT-SUN on 2017/4/15.
 */
$(function () {
    $('#btn_save').on('click', function () {
        submitForm();
    });
    checkBoxFun();
    /**
     * 绑定监测单位选择事件
     */
    $("#serviceId").textbox({
        iconWidth: 20,
        icons: [{
            iconCls: 'icon-add',
            handler: function(e){
                openSerViceTb();
            }
        },{
            iconCls: 'icon-remove',
            handler: function(e){
                $(e.data.target).textbox('clear');

            }
        }]
    });
    var OHE_HEALTH_OPTIONS=CONSTANT.DictionaryTypeDefConstants.OHE_HEALTH_OPTIONS;//处理意见
    queryComboData(OHE_HEALTH_OPTIONS,'options');

    /**
     * 绑定人员选择事件
     */
    $("#userId").textbox({
        iconWidth: 20,
        icons: [{
            iconCls: 'icon-add',
            handler: function(e){
                add_userId_func();
            }
        }]
    });

    $("#physicalBatch").textbox({
        iconWidth: 20,
        icons: [{
            iconCls: 'icon-add',
            handler: function(e){
                add_physical_func();
            }
        },{
            iconCls: 'icon-remove',
            handler: function(e){
                $(e.data.target).textbox('clear');
                $("#leibie").textbox('setValue', '').textbox('setText', '');
            }
        }]
    });
    $("#zyweihai").textbox({
        iconWidth: 20,
        icons: [{
            iconCls: 'icon-add',
            handler: function(e){
                add_hazardFactor_func();
            }
        },{
            iconCls: 'icon-remove',
            handler: function(e){
                $(e.data.target).textbox('clear');
                $("#zyweihaiId").val('');
            }
        }]
    });
    initOccTbDiv();
});
var add_hazardFactor_func=function () {
    WindowManager.openLayer({
        type: 2,
        title: '选择危害因素',
        area: ['900px', '60%'],
        content: ROOT_PATH + '/occupationalHealth/hazardFactor/listTb.shtml?isMulti=1',
        callBack:function(data){
            getSelectedFactor(data);
        }
    });
};
var getSelectedFactor = function (data) {
    if (data.length>1){
        var names = '';
        var ids='';
        for (var index in data) {
            names += ',' + data[index].name;
            ids += ',' + data[index].id;
        }
        $("#zyweihai").textbox('setValue', ids.substring(1)).textbox('setText', names.substring(1));
        $("#zyweihaiId").val(ids.substring(1));
    }else {
        $("#zyweihai").textbox('setValue', data[0].id).textbox('setText', data[0].name);
        $("#zyweihaiId").val(data[0].id);
    }
};
var editIndex_occforbidTb = undefined;//职业禁忌证
var editIndex_occdoubtTb = undefined;//疑似职业病
var editIndex_occotherTb = undefined;//其它疾病或异常


function endEditingFtb(){
    if (editIndex_occforbidTb == undefined){return true}
    if ($('#occforbidTb').datagrid('validateRow', editIndex_occforbidTb)){
        $('#occforbidTb').datagrid('endEdit', editIndex_occforbidTb);
        editIndex_occforbidTb = undefined;
        return true;
    } else {
        return false;
    }
}
function endEditingDtb(){
    if (editIndex_occdoubtTb == undefined){return true}
    if ($('#occdoubtTb').datagrid('validateRow', editIndex_occdoubtTb)){
        $('#occdoubtTb').datagrid('endEdit', editIndex_occdoubtTb);
        editIndex_occdoubtTb = undefined;
        return true;
    } else {
        return false;
    }
}
function endEditingOtb(){
    if (editIndex_occotherTb == undefined){return true}
    if ($('#occotherTb').datagrid('validateRow', editIndex_occotherTb)){
        $('#occotherTb').datagrid('endEdit', editIndex_occotherTb);
        editIndex_occotherTb = undefined;
        return true;
    } else {
        return false;
    }
}
function initOccTbDiv() {
    //职业禁忌证occotherTb_save
    $('#occforbidTb_save').on('click', function () {
        if (endEditingFtb()){
            $('#occforbidTb').datagrid('acceptChanges');
        }
        /*$('#occforbidTb').datagrid('clearSelections');*/
    });
    $('#occforbidTb_add').on('click', function () {
        if ($("#userId").val()==''){
            layer.alert("请先选择人员！");
            return;
        }
        if (endEditingDtb()){}
        if (endEditingOtb()){}
        var valueUserId=$("#userId").textbox('getValue');
        if (endEditingFtb()){
            $('#occforbidTb').datagrid('appendRow',{
                userId: valueUserId
            });
            editIndex_occforbidTb = $('#occforbidTb').datagrid('getRows').length-1;
            $('#occforbidTb').datagrid('selectRow', editIndex_occforbidTb).datagrid('beginEdit', editIndex_occforbidTb);
        }
    });
    $('#occforbidTb_remove').on('click', function () {
        if (editIndex_occforbidTb == undefined){return}
        $('#occforbidTb').datagrid('cancelEdit', editIndex_occforbidTb).datagrid('deleteRow', editIndex_occforbidTb);
        editIndex_occforbidTb = undefined;
    });
    //疑似职业病
    $('#occdoubtTb_save').on('click', function () {
        if (endEditingDtb()){
            $('#occdoubtTb').datagrid('acceptChanges');
        }
    });
    $('#occdoubtTb_add').on('click', function () {
        if ($("#userId").val()==''){
            layer.alert("请先选择人员！");
            return;
        }
        if (endEditingFtb()){}
        if (endEditingOtb()){}
        var valueUserId=$("#userId").textbox('getValue');
        if (endEditingDtb()){
            $('#occdoubtTb').datagrid('appendRow',{
                userId: valueUserId
            });
            editIndex_occdoubtTb = $('#occdoubtTb').datagrid('getRows').length-1;
            $('#occdoubtTb').datagrid('selectRow', editIndex_occdoubtTb).datagrid('beginEdit', editIndex_occdoubtTb);
        }
    });
    $('#occdoubtTb_remove').on('click', function () {
        if (editIndex_occdoubtTb == undefined){return}
        $('#occdoubtTb').datagrid('cancelEdit', editIndex_occdoubtTb).datagrid('deleteRow', editIndex_occdoubtTb);
        editIndex_occdoubtTb = undefined;
    });
    //其它疾病或异常
    $('#occotherTb_save').on('click', function () {
        if (endEditingOtb()){
            $('#occotherTb').datagrid('acceptChanges');
        }
    });
    $('#occotherTb_add').on('click', function () {
        if ($("#userId").val()==''){
            layer.alert("请先选择人员！");
            return;
        }
        if (endEditingFtb()){}
        if (endEditingDtb()){}
        var valueUserId=$("#userId").textbox('getValue');
        if (endEditingOtb()){
            $('#occotherTb').datagrid('appendRow',{
                userId: valueUserId
            });
            editIndex_occotherTb = $('#occotherTb').datagrid('getRows').length-1;
            $('#occotherTb').datagrid('selectRow', editIndex_occotherTb).datagrid('beginEdit', editIndex_occotherTb);
        }
    });
    $('#occotherTb_remove').on('click', function () {
        if (editIndex_occotherTb == undefined){return}
        $('#occotherTb').datagrid('cancelEdit', editIndex_occotherTb).datagrid('deleteRow', editIndex_occotherTb);
        editIndex_occotherTb = undefined;
    });
}
/**
 * 职业禁忌
 */
function occforbidTb() {
    $('#occforbidTb').datagrid({
        fitColumns: true,
        //pagination: true,
        rownumbers: true,
        sortOrder: true,
        singleSelect: true,
        striped: true,
        fit: false,
        height: 300,
        columns: [[
            {field: 'forbidName', title: '职业禁忌证名称', width: 100,editor: { type: 'validatebox', options: { required: true } }},
            {field: 'forbidWork', title: '禁忌作业', width: 100,editor: { type: 'textbox' }},
            {field: 'remarks', title: '备注', width: 100,editor: { type: 'textbox'}},
            {field: 'userId', title: 'userId', hidden:true,width: 100}
        ]],
        onClickRow:function (index,  value) {
            if (editIndex_occforbidTb != index){
                if (endEditingFtb()){
                    $('#occforbidTb').datagrid('selectRow', index).datagrid('beginEdit', index);
                    editIndex_occforbidTb = index;
                }else {
                    $('#occforbidTb').datagrid('selectRow', editIndex_occforbidTb);
                }
            }
        }
    });
}
/**
 * 疑似职业病
 */
function occdoubtTb() {
    $('#occdoubtTb').datagrid({
        fitColumns: true,
        //pagination: true,
        rownumbers: true,
        sortOrder: true,
        singleSelect: true,
        striped: true,
        fit: false,
        height: 300,
        columns: [[
            /*{
                field: 'NumId',
                checkbox: true
            },*/
            {field: 'diseasesNameId', hidden:true,title: '职业病名称Id', width: 100,editor: {
                type: 'textbox',
                options:{
                    //required:true
                }
            }},
            {field: 'diseasesName', title: '职业病名称', width: 100,
                editor: {
                    type: 'textbox',
                    options:{
                        iconWidth: 20,
                        editable:false,
                        required:true,
                        icons: [{
                            iconCls: 'icon-add',
                            handler: function(e){
                                add_dis_func();
                            }
                        },{
                            iconCls: 'icon-remove',
                            handler: function(e){
                                $(e.data.target).textbox('clear');
                                var edId = $("#occdoubtTb").datagrid('getEditor', { index: editIndex_occdoubtTb, field: 'diseasesNameId' });
                                var edCode = $("#occdoubtTb").datagrid('getEditor', { index: editIndex_occdoubtTb, field: 'diseasesCode' });
                                $(edId.target).textbox('setValue', '').textbox('setText', '');
                                $(edCode.target).textbox('setValue', '').textbox('setText', '');
                            }
                        }]
                    }
                }},
            {field: 'diseasesCode', title: '编码', width: 100,editor: { type: 'textbox',options:{
                readonly:true
                //required:true
            } }},
            {field: 'remarks', title: '备注', width: 100,editor: { type: 'textbox'}},
            {field: 'userId', title: 'userId', hidden:true,width: 100}
        ]],
        onClickRow:function (index, field, value) {
            if (editIndex_occdoubtTb != index){
                if (endEditingDtb()){
                    $('#occdoubtTb').datagrid('selectRow', index).datagrid('beginEdit', index);
                    editIndex_occdoubtTb = index;
                }else {
                    $('#occdoubtTb').datagrid('selectRow', editIndex_occdoubtTb);
                }
            }
        }
    });
}
/**
 * 其它疾病或异常
 */
function occotherTb() {
    $('#occotherTb').datagrid({
        fitColumns: true,
       // pagination: true,
        rownumbers: true,
        sortOrder: true,
        singleSelect: true,
        striped: true,
        fit: false,
        height: 300,
        columns: [[
            {field: 'diseasesName', title: '疾病名称', width: 100,editor: { type: 'validatebox', options: { required: true } }},
            {field: 'remarks', title: '备注', width: 100,editor: { type: 'textbox'}},
            {field: 'userId', title: 'userId', hidden:true,width: 100}
        ]],
        onClickRow:function (index, field, value) {
            if (editIndex_occotherTb != index){
                if (endEditingOtb()){
                    $('#occotherTb').datagrid('selectRow', index).datagrid('beginEdit', index);
                    editIndex_occotherTb = index;
                }else {
                    $('#occotherTb').datagrid('selectRow', editIndex_occotherTb);
                }
            }
        }
    });
}
function openSerViceTb() {
    WindowManager.openLayer({
        type: 2,
        title: '选择服务机构',
        area: ['850px', '70%'],
        content: ROOT_PATH + '/occupationalHealth/hseServiceOrg/orgTb.shtml',
        callBack:function(data){
            getSelectedOrg(data);
        }
    });
}
function getSelectedOrg(data) {
    $("#serviceId").textbox('setValue', data[0].id).textbox('setText', data[0].serviceName);
}
var add_userId_func = function () {
    WindowManager.openLayer({
        type: 2,
        title: '选择人员信息',
        area: ['1150px', '70%'],
        content: ROOT_PATH + '/permission/user/simpleList.shtml?isMulti=0',
        callBack:function(data){
            getSelectedUser(data);
        }
    });
};

function add_dis_func() {
    WindowManager.openLayer({
        type: 2,
        title: '选择职业病',
        area: ['850px', '70%'],
        content: ROOT_PATH + '/occupationalHealth/occDiseases/disTb.shtml',
        callBack:function(data){
            getSelectedDis(data);
        }
    });
}
function getSelectedDis(data) {
    var ed = $("#occdoubtTb").datagrid('getEditor', { index: editIndex_occdoubtTb, field: 'diseasesName' });
    var edId = $("#occdoubtTb").datagrid('getEditor', { index: editIndex_occdoubtTb, field: 'diseasesNameId' });
    var edCode = $("#occdoubtTb").datagrid('getEditor', { index: editIndex_occdoubtTb, field: 'diseasesCode' });
    $(ed.target).textbox('setValue', data[0].diseasesName).textbox('setText', data[0].diseasesName);
    $(edId.target).textbox('setValue', data[0].id).textbox('setText', data[0].id);
    $(edCode.target).textbox('setValue', data[0].diseasesCode).textbox('setText', data[0].diseasesCode);
}
/**
 * 体检批次选择
 */
function add_physical_func() {
    WindowManager.openLayer({
        type: 2,
        title: '选择体检批次',
        area: ['1000px', '70%'],
        content: ROOT_PATH + '/occupationalHealth/medicalPlan/planTb.shtml',
        callBack:function(data){
            getSelectedPlan(data);
        }
    });
}
function getSelectedPlan(data) {
    $("#physicalBatch").textbox('setValue', data[0].id).textbox('setText', data[0].batch);
    $("#leibie").textbox('setValue', data[0].medicalCategory).textbox('setText', data[0].medicalCategory);
}
/**
 * 人员信息选择
 */
var getSelectedUser = function (data) {
    if(data.length>0){
        $("#userId").textbox('setValue', data[0].id).textbox('setText', data[0].realName);
        var deptName='';
        if (data[0].userDepartmentList && data[0].userDepartmentList.length > 0) {
            for (var index in data[0].userDepartmentList) {
                if (data[0].userDepartmentList[index].deptName != null) {
                    deptName += ',' + data[0].userDepartmentList[index].deptName;
                }
            }
            deptName= deptName.substring(1);
        } else {
            deptName='';
        }
        $("#danwei").textbox('setValue', deptName).textbox('setText', deptName);
        $("#gonghao").textbox('setValue', data[0].code).textbox('setText', data[0].code);
        $("#gangwei").textbox('setValue', data[0].postName).textbox('setText', data[0].postName);
        if (data[0].userInfo!=null){
            var gender='';
            if (data[0].userInfo.gender=='1'){
                gender='男'
            }
            if (data[0].userInfo.gender=='0'){
                gender='女'
            }
            $("#xingbie").textbox('setValue', gender).textbox('setText', gender);
        }
    }
};
function submitForm() {
    if (!$('#formPhyData').form('validate')) { layer.alert("请正确填写信息"); return $('#formPhyData').form('validate');}
    var ckL=$("input[name='conclusion']:checked");
    if (ckL.length==0){
        layer.alert("请选体检结论！");
        return;
    }
    if($("#conclusionNo").is(":checked")){

    }else {
        if ($("#options").val()==""){
            layer.alert("请选择处理意见！");
            return;
        }
    }
    var objParams = $('#formPhyData').serializeJson();//
    if(typeof (objParams.conclusion)=='undefined'){
        layer.alert("请选择体检结论！");
        return;
    }
    if($("#conclusionZy").is(":checked")){
        if (endEditingFtb()){
            $('#occforbidTb').datagrid('acceptChanges');
        }
        var objArr1=$('#occforbidTb').datagrid('getData');
        if(objArr1.total>0){
            var occforbidTb= JSON.stringify(objArr1.rows);
            objParams.occforbidTb=occforbidTb;
        }else {
            layer.alert("请添加职业禁忌证数据或者取消勾选！");
            return;
        }
    }
    if($("#conclusionYs").is(":checked")){
        if (endEditingDtb()){
            $('#occdoubtTb').datagrid('acceptChanges');
        }
        var objArr2=$('#occdoubtTb').datagrid('getData');
        if(objArr2.total>0){
            var occdoubtTb= JSON.stringify(objArr2.rows);
            objParams.occdoubtTb=occdoubtTb;
        }else {
            layer.alert("请添加疑似职业病数据或者取消勾选！");
            return;
        }
    }
    if($("#conclusionQt").is(":checked")){
        if (endEditingOtb()){
            $('#occotherTb').datagrid('acceptChanges');
        }
        var objArr3=$('#occotherTb').datagrid('getData');
        if(objArr3.total>0){
            var occotherTb= JSON.stringify(objArr3.rows);
            objParams.occotherTb=occotherTb;
        }else {
            layer.alert("请添其它疾病数据或者取消勾选！");
            return;
        }
    }
    $.ajax({
        url:ROOT_PATH + '/occupationalHealth/phyData/insertSelective.shtml',//提交地址
        data:objParams,
        type:"POST",
        dataType:"json",
        //contentType:"application/json",
        success: function (result) {
            if (result.success) {
                layer.msg('保存成功', {
                    icon: 1,
                    time: 1000
                }, function () {
                    WindowManager.closeLayer({
                        returnValue: true
                    });
                });
            }
            else {
                layer.msg('保存失败', {
                    icon: 2,
                    time: 1000
                });
            }
        }
    });
}
function queryComboData(code,queryId) {
    var EMPTY_OPTION = {
     id: '',
     text: '请选择'
     };
    var pageId='#'+queryId;
    $.ajax({
        type: 'post',
        url: ROOT_PATH + '/permission/dictionary/queryDictionaryByDictionaryTypeCode.shtml',
        data: {code: code},
        dataType: "json",
        success: function (result) {
            $(pageId).combobox({
                loadFilter: function (data) {
                 data.unshift(EMPTY_OPTION);
                 return data;
                 },
                data: result,
                valueField: 'id',
                textField: 'text',
                editable: false,
                panelHeight: '200',
            });
        }
    });
}

function checkBoxFun() {
    $("#conclusionNo").click(function () {
        if($(this).is(":checked")) {
            $("#optionDiv").hide();
            $(".optiony").attr("checked",false);
            $("#occforbidTbDiv").hide();
            $("#occdoubtTbDiv").hide();
            $("#occotherTbDiv").hide();
            $("#isAbnormal").val('0');
        }
    });
    $("#conclusionFx").click(function () {
        if($(this).is(":checked")) {
            $("#optionDiv").show();
            $("#conclusionNo").attr("checked",false);
            $("#isAbnormal").val('1');
        }
    });
    $("#conclusionZy").click(function () {
        if($(this).is(":checked")) {
            $("#optionDiv").show();
            $("#occforbidTbDiv").show();
            $("#conclusionNo").attr("checked",false);
            $("#isAbnormal").val('1');
            occforbidTb();
        }else {
            $("#occforbidTbDiv").hide();
        }
    });
    $("#conclusionYs").click(function () {
        if($(this).is(":checked")) {
            $("#optionDiv").show();
            $("#occdoubtTbDiv").show();
            $("#conclusionNo").attr("checked",false);
            $("#isAbnormal").val('1');
            occdoubtTb();
        }else {
            $("#occdoubtTbDiv").hide();
        }
    });
    $("#conclusionQt").click(function () {
        if($(this).is(":checked")) {
            $("#optionDiv").show();
            $("#occotherTbDiv").show();
            $("#conclusionNo").attr("checked",false);
            $("#isAbnormal").val('1');
            occotherTb();
        }else {
            $("#occotherTbDiv").hide();
        }
    });
}
